﻿using System;
using System.Collections.Generic;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.ViewManagement;
using System.Linq;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Controls.Primitives;
using System.Net;
using System.Runtime.Serialization.Json;
using Windows.UI.Popups;

namespace WellDone
{
    public sealed partial class CloseOrder : Page
    {
        public event EventHandler CloseRequested;
        public int iCurrentSeat = 0;
        decimal decCurrentTotal = 0;
        public int iSplitCount = 0;
        public int iOrderNO = -1;
        public int iTableNO = -1;
        public int iCheckNo = 0;
        public bool bTaxExempt = false;
        private ListView lvMenuItems = null;
        Popup subDialogPopup;
        public static int partialCheckNo;
        public static decimal partialCashAmount;
        public static decimal partialCreditAmount;
        public static string AuthCode;

        private int orderDiscount = -1;  // Set DiscountID For Whole Order
        bool IsDiscount = false;  // Discount is Applied or not  
        public int iOrderDiscount
        {
            get
            {
                return orderDiscount;
            }
            set
            {
                orderDiscount = value;
                if (IsDiscount == false && orderDiscount > 0) IsDiscount = true;
            }
        }
        public void init()
        {
            var pane = InputPane.GetForCurrentView();
            pane.Showing += pane_Showing;
            pane.Hiding += pane_Hiding;
        }
        private void pane_Showing(InputPane sender, InputPaneVisibilityEventArgs e)
        {
            // Shift the dialog up...
            this.RootPanel.Margin = new Thickness(0, -1 * e.OccludedRect.Y, 0, 0);
        }
        private void pane_Hiding(InputPane sender, InputPaneVisibilityEventArgs e)
        {
            // Restore...
            this.RootPanel.Margin = new Thickness(0, 0, 0, 0);
        }

        public CloseOrder()
        {
            this.InitializeComponent();
        }

        public void addOrderDetailItem(ItemCollection itemCollection)
        {
            // Add passed item to the list
            lvMenuItems = new ListView();   // main list view container by whick we can move item to other check 

            foreach (OrderData od in itemCollection)
            {
                lvMenuItems.Items.Add(od);
                lvMenuItems.ScrollIntoView(od);
                if (od.MenuItemID == 0 && od.OpenItemID == 0) //  check if it is discount item
                {
                    if (IsDiscount == false && od.DiscountID != 0) IsDiscount = true; // set  discount  if it is item wise 
                }

                decCurrentTotal += od.Price;
            }
        }

        public void addChecks(int CheckCount)
        {
            decCurrentTotal = 0;
            int tmpCount = 0;
            while (tmpCount < CheckCount)
            {
                try
                {
                    Canvas tmpCanvas = new Canvas();
                    tmpCanvas.Margin = new Thickness(((300 * tmpCount)), 0, 0, 0);
                    Border tmpBorder = new Border();
                    tmpBorder.BorderThickness = new Thickness(2);
                    tmpBorder.BorderBrush = new SolidColorBrush(Colors.Black);
                    tmpBorder.Background = new SolidColorBrush(Colors.LightGray);
                    tmpBorder.HorizontalAlignment = HorizontalAlignment.Left;
                    tmpBorder.VerticalAlignment = VerticalAlignment.Top;
                    tmpBorder.Width = 300;
                    tmpBorder.Height = 640;

                    Grid GridSplitCheck = new Grid();
                    GridSplitCheck.Margin = new Thickness(2);
                    RowDefinition gridRow1 = new RowDefinition();
                    gridRow1.Height = new GridLength(40);
                    RowDefinition gridRow2 = new RowDefinition();
                    gridRow2.Height = new GridLength(40);
                    RowDefinition gridRow3 = new RowDefinition();
                    gridRow3.Height = new GridLength(145);
                    RowDefinition gridRow4 = new RowDefinition();
                    gridRow4.Height = new GridLength(40);

                    RowDefinition gridRow5 = new RowDefinition();
                    gridRow5.Height = new GridLength(290);

                    RowDefinition gridRow6 = new RowDefinition();
                    gridRow6.Height = new GridLength(90);

                    GridSplitCheck.RowDefinitions.Add(gridRow1);
                    GridSplitCheck.RowDefinitions.Add(gridRow2);
                    GridSplitCheck.RowDefinitions.Add(gridRow3);
                    GridSplitCheck.RowDefinitions.Add(gridRow4);
                    GridSplitCheck.RowDefinitions.Add(gridRow5);
                    GridSplitCheck.RowDefinitions.Add(gridRow6);

                    #region create header strip row
                    /*create header strip row*/
                    Grid GridSplitCheckHeaderstrip = new Grid();
                    GridSplitCheckHeaderstrip.Background = new SolidColorBrush(Colors.LightGray);
                    ColumnDefinition gridColstrip1 = new ColumnDefinition();

                    GridSplitCheckHeaderstrip.ColumnDefinitions.Add(gridColstrip1);
                    ColumnDefinition gridColstrip2 = new ColumnDefinition();
                    gridColstrip2.Width = new GridLength(40);
                    GridSplitCheckHeaderstrip.ColumnDefinitions.Add(gridColstrip2);
                    TextBlock lblHeaderstrip = new TextBlock();
                    lblHeaderstrip.Text = "Check # " + (tmpCount + 1);
                    lblHeaderstrip.FontSize = 20;
                    lblHeaderstrip.Margin = new Thickness(5, 4, 0, 0);
                    Grid.SetColumn(lblHeaderstrip, 0);
                    GridSplitCheckHeaderstrip.Children.Add(lblHeaderstrip);

                    Border tmpBorderstrip = new Border();
                    tmpBorderstrip.BorderThickness = new Thickness(2);
                    tmpBorderstrip.BorderBrush = new SolidColorBrush(Colors.Black);

                    tmpBorderstrip.Child = GridSplitCheckHeaderstrip;
                    Grid.SetRow(tmpBorderstrip, 0);
                    GridSplitCheck.Children.Add(tmpBorderstrip);
                    #endregion

                    #region create header row

                    /*create header row*/
                    Grid GridSplitCheckHeader = new Grid();
                    GridSplitCheckHeader.Background = new SolidColorBrush(Colors.LightGray);
                    ColumnDefinition gridCol1 = new ColumnDefinition();
                    ColumnDefinition gridCol2 = new ColumnDefinition();

                    GridSplitCheckHeader.ColumnDefinitions.Add(gridCol1);
                    GridSplitCheckHeader.ColumnDefinitions.Add(gridCol2);

                    TextBlock lblHeader1 = new TextBlock();
                    lblHeader1.Text = "Item";
                    lblHeader1.FontSize = 20;
                    lblHeader1.Margin = new Thickness(5, 4, 0, 0);
                    Grid.SetColumn(lblHeader1, 0);

                    TextBlock lblHeader2 = new TextBlock();
                    lblHeader2.Text = "Price";
                    lblHeader2.FontSize = 20;
                    lblHeader2.HorizontalAlignment = HorizontalAlignment.Right;
                    lblHeader2.Margin = new Thickness(0, 4, 15, 0);
                    Grid.SetColumn(lblHeader2, 1);

                    GridSplitCheckHeader.Children.Add(lblHeader1);
                    GridSplitCheckHeader.Children.Add(lblHeader2);

                    Grid.SetRow(GridSplitCheckHeader, 1);
                    GridSplitCheck.Children.Add(GridSplitCheckHeader);
                    #endregion

                    #region create item list row


                    /*create item list row*/
                    ListView lstMenuItems = new ListView();
                    lstMenuItems.HorizontalAlignment = HorizontalAlignment.Center;
                    lstMenuItems.Height = 145;
                    lstMenuItems.Margin = new Thickness(0);
                    lstMenuItems.BorderThickness = new Thickness(0);
                    lstMenuItems.Background = new SolidColorBrush(Colors.White);
                    lstMenuItems.VerticalAlignment = VerticalAlignment.Top;
                    lstMenuItems.Width = 296;
                    lstMenuItems.ItemContainerStyle = this.Resources["ListViewItemStyleOpenRPOS"] as Style;
                    lstMenuItems.IsSwipeEnabled = false;
                    lstMenuItems.SelectionMode = ListViewSelectionMode.Multiple;
                    lstMenuItems.Tag = tmpCount;
                    lstMenuItems.ItemTemplate = MenuItems.ItemTemplate; //copy same itemtemplate as original / main list

                    MoveItemsInChecks(lvMenuItems, lstMenuItems); //move menu items from main check to appropriate check

                    Grid.SetRow(lstMenuItems, 2);
                    GridSplitCheck.Children.Add(lstMenuItems);

                    #endregion

                    #region create footer row

                    /*create footer row*/
                    Grid GridSplitCheckFooter = new Grid();
                    GridSplitCheckFooter.Background = new SolidColorBrush(Colors.LightGray);
                    gridCol1 = new ColumnDefinition();
                    gridCol2 = new ColumnDefinition();

                    GridSplitCheckFooter.ColumnDefinitions.Add(gridCol1);
                    GridSplitCheckFooter.ColumnDefinitions.Add(gridCol2);

                    lblHeader1 = new TextBlock();
                    lblHeader1.Text = "Subtotal";
                    lblHeader1.FontSize = 20;
                    lblHeader1.Margin = new Thickness(5, 4, 0, 0);
                    Grid.SetColumn(lblHeader1, 0);

                    TextBlock lblOrderTotal = new TextBlock();
                    decCurrentTotal = 0;
                    decimal iTotal = 0;
                    decimal iDetailDiscountTotal = 0; // Discount  Total if discount is item wise 

                    foreach (OrderData od in lstMenuItems.Items)
                    {
                        decCurrentTotal += od.Price;
                        if (od.Discount && (od.MenuItemID == 0)) iDetailDiscountTotal += (-1 * od.Price);
                    }
                    iTotal = decCurrentTotal;

                    lblOrderTotal.Text = iTotal.ToString("N");
                    lblOrderTotal.FontSize = 28;
                    lblOrderTotal.HorizontalAlignment = HorizontalAlignment.Left;
                    lblOrderTotal.Margin = new Thickness(0, 4, 0, 0);
                    lblOrderTotal.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    Grid.SetColumn(lblOrderTotal, 1);

                    TextBlock lblDiscountTotal = new TextBlock();
                    lblDiscountTotal.Text = iTotal.ToString("N");
                    lblDiscountTotal.Inlines.Add(new Run() { Text = (IsDiscount == false ? "" : "(" + (-1 * iDetailDiscountTotal).ToString("N") + ")"), Foreground = new SolidColorBrush(Colors.Red) });
                    lblDiscountTotal.FontSize = 20;
                    lblDiscountTotal.HorizontalAlignment = HorizontalAlignment.Right;
                    lblDiscountTotal.Width = 140;
                    lblDiscountTotal.TextAlignment = TextAlignment.Right;
                    lblDiscountTotal.Margin = new Thickness(0, 4, 5, 0);
                    Grid.SetColumn(lblDiscountTotal, 1);


                    GridSplitCheckFooter.Children.Add(lblHeader1);
                    GridSplitCheckFooter.Children.Add(lblOrderTotal);
                    GridSplitCheckFooter.Children.Add(lblDiscountTotal);

                    Grid.SetRow(GridSplitCheckFooter, 3);
                    GridSplitCheck.Children.Add(GridSplitCheckFooter);

                    #endregion

                    #region create header strip row for Payment method


                    /*create header strip row for Payment method*/
                    Grid GridCloseCheckTypeStrip = new Grid();
                    GridCloseCheckTypeStrip.Height = 280;
                    GridCloseCheckTypeStrip.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    GridCloseCheckTypeStrip.Background = new SolidColorBrush(Colors.White);
                    ColumnDefinition GridCloseCheckTypeStripColstrip1 = new ColumnDefinition();
                    GridCloseCheckTypeStrip.ColumnDefinitions.Add(GridCloseCheckTypeStripColstrip1);

                    ColumnDefinition GridCloseCheckTypeStripColstrip2 = new ColumnDefinition();
                    GridCloseCheckTypeStripColstrip2.Width = new GridLength(180);
                    GridCloseCheckTypeStrip.ColumnDefinitions.Add(GridCloseCheckTypeStripColstrip2);

                    RowDefinition GridCloseCheckTypeStrip1 = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridCloseCheckTypeStrip1);

                    RowDefinition GridRowForPaymentMode = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForPaymentMode);

                    RowDefinition GridRowForPaymentMode1 = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForPaymentMode1);

                    RowDefinition GridRowForTip = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForTip);
                    RowDefinition GridRowFortax = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowFortax);
                    RowDefinition GridRowForTotal = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForTotal);
                    RowDefinition GridRowForpayment = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForpayment);
                    RowDefinition GridRowForChange = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForChange);
                    RowDefinition GridRowForAuthCode = new RowDefinition();
                    GridCloseCheckTypeStrip.RowDefinitions.Add(GridRowForAuthCode);

                    #region Payment method

                    TextBlock lblHeaderGridCloseCheckType = new TextBlock();
                    lblHeaderGridCloseCheckType.Text = "Payment method";
                    lblHeaderGridCloseCheckType.FontSize = 20;
                    lblHeaderGridCloseCheckType.Margin = new Thickness(5, 4, 0, 0);
                    Grid.SetRow(lblHeaderGridCloseCheckType, 0);
                    Grid.SetColumnSpan(lblHeaderGridCloseCheckType, 2);
                    GridCloseCheckTypeStrip.Children.Add(lblHeaderGridCloseCheckType);

                    RadioButton rdbHeaderGridCloseCheckType1 = new RadioButton();
                    rdbHeaderGridCloseCheckType1.CommandParameter = "Cash";
                    rdbHeaderGridCloseCheckType1.Name = "Cash" + tmpCount;
                    rdbHeaderGridCloseCheckType1.IsChecked = Globals.OrderCheckRecords[tmpCount].col_PaymentType == 0 ? true : false;
                    rdbHeaderGridCloseCheckType1.GroupName = tmpCount.ToString();
                    rdbHeaderGridCloseCheckType1.Content = "Cash";
                    rdbHeaderGridCloseCheckType1.FontSize = 20;
                    rdbHeaderGridCloseCheckType1.Margin = new Thickness(0);
                    rdbHeaderGridCloseCheckType1.Padding = new Thickness(3, -2, 0, 0);
                    rdbHeaderGridCloseCheckType1.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    rdbHeaderGridCloseCheckType1.Checked += rdbHeaderGridCloseCheckType1_Checked;

                    Grid.SetRow(rdbHeaderGridCloseCheckType1, 1);
                    Grid.SetColumn(rdbHeaderGridCloseCheckType1, 0);
                    GridCloseCheckTypeStrip.Children.Add(rdbHeaderGridCloseCheckType1);

                    RadioButton rdbHeaderGridCloseCheckType2 = new RadioButton();
                    rdbHeaderGridCloseCheckType2.CommandParameter = "CreditDebit";
                    rdbHeaderGridCloseCheckType2.IsChecked = Globals.OrderCheckRecords[tmpCount].col_PaymentType == 1 ? true : false;
                    rdbHeaderGridCloseCheckType2.Content = "Credit/Debit";
                    rdbHeaderGridCloseCheckType2.Name = "CreditDebit" + tmpCount;
                    rdbHeaderGridCloseCheckType2.GroupName = tmpCount.ToString();
                    rdbHeaderGridCloseCheckType2.FontSize = 20;
                    rdbHeaderGridCloseCheckType2.Margin = new Thickness(0);
                    rdbHeaderGridCloseCheckType2.Padding = new Thickness(3, -2, 0, 0);
                    rdbHeaderGridCloseCheckType2.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    rdbHeaderGridCloseCheckType2.Checked += rdbHeaderGridCloseCheckType1_Checked;

                    Grid.SetRow(rdbHeaderGridCloseCheckType2, 1);
                    Grid.SetColumn(rdbHeaderGridCloseCheckType2, 1);
                    GridCloseCheckTypeStrip.Children.Add(rdbHeaderGridCloseCheckType2);


                    RadioButton rdbHeaderGridCloseCheckType3 = new RadioButton();
                    rdbHeaderGridCloseCheckType3.CommandParameter = "Other";
                    rdbHeaderGridCloseCheckType3.IsChecked = Globals.OrderCheckRecords[tmpCount].col_PaymentType > 1 ? true : false;
                    rdbHeaderGridCloseCheckType3.Content = "Other";
                    rdbHeaderGridCloseCheckType3.Name = "Other" + tmpCount;
                    rdbHeaderGridCloseCheckType3.GroupName = tmpCount.ToString();
                    rdbHeaderGridCloseCheckType3.FontSize = 20;
                    rdbHeaderGridCloseCheckType3.Margin = new Thickness(0);
                    rdbHeaderGridCloseCheckType3.Padding = new Thickness(3, -2, 0, 0);
                    rdbHeaderGridCloseCheckType3.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    rdbHeaderGridCloseCheckType3.Checked += rdbHeaderGridCloseCheckType1_Checked;

                    Grid.SetRow(rdbHeaderGridCloseCheckType3, 2);
                    Grid.SetColumn(rdbHeaderGridCloseCheckType3, 0);
                    GridCloseCheckTypeStrip.Children.Add(rdbHeaderGridCloseCheckType3);

                    ComboBox cbPaymenttype = new ComboBox();
                    cbPaymenttype.Name = "cbPaymenttype" + tmpCount;
                    cbPaymenttype.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cbPaymenttype.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    cbPaymenttype.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    cbPaymenttype.Margin = new Thickness(0);
                    cbPaymenttype.FontSize = 20;
                    cbPaymenttype.Width = 170;
                    cbPaymenttype.Height = 35;
                    cbPaymenttype.Margin = new Thickness(5, -2, 0, 0);
                    if (Globals.PaymentTypeRecords.Count > 0)
                    {
                        foreach (ServiceReferenceOpenRPOS.PaymentType paymenttype in Globals.PaymentTypeRecords)
                        {
                            cbPaymenttype.Items.Add(paymenttype.col_Name);
                        }
                        cbPaymenttype.SelectedIndex = 0;
                    }

                    if (cbPaymenttype.Items.Count() > 0)
                    {
                        foreach (ServiceReferenceOpenRPOS.PaymentType pt in Globals.PaymentTypeRecords)
                        {
                            if (pt.col_ID == Globals.OrderCheckRecords[tmpCount].col_PaymentType)
                                cbPaymenttype.SelectedItem = pt.col_Name;
                        }
                    }
                    Grid.SetRow(cbPaymenttype, 2);
                    Grid.SetColumn(cbPaymenttype, 1);
                    GridCloseCheckTypeStrip.Children.Add(cbPaymenttype);
                    #endregion

                    #region Tip

                    TextBlock lbltip = new TextBlock();
                    lbltip.Text = "Tip";
                    lbltip.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                    lbltip.FontSize = 20;
                    lbltip.Margin = new Thickness(5, 8, 4, 0);
                    Grid.SetRow(lbltip, 3);
                    Grid.SetColumn(lbltip, 0);
                    GridCloseCheckTypeStrip.Children.Add(lbltip);

                    // Default to a numeric keyboard
                    InputScope tipScope = new InputScope();
                    InputScopeName tipScopeName = new InputScopeName();
                    tipScopeName.NameValue = InputScopeNameValue.Number;
                    tipScope.Names.Add(tipScopeName);

                    TextBox txtTip = new TextBox();
                    txtTip.InputScope = tipScope;
                    txtTip.Name = "txtTip" + tmpCount;
                    txtTip.TextChanged += txtTip_TextChanged;
                    txtTip.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    txtTip.Width = 170;
                    txtTip.Text = Globals.OrderCheckRecords[tmpCount].col_Gratuity.ToString("N");
                    /*
                    if (Globals.OrderCheckRecords.Count > 0)
                    {
                        if (Globals.OrderCheckRecords[tmpCount].col_ID != 0)
                        {
                            txtTip.IsEnabled = false;
                        }
                        else
                        {
                            txtTip.IsEnabled = true;
                        }
                    }*/
                    txtTip.FontSize = 20;
                    txtTip.Margin = new Thickness(5, 0, 0, 0);
                    txtTip.MaxLength = 9;
                    Color highlightColor = new Color();
                    highlightColor.A = 255;
                    highlightColor.R = 152;
                    highlightColor.G = 222;
                    highlightColor.B = 248;
                    txtTip.SelectionHighlightColor = new SolidColorBrush(highlightColor);
                    Grid.SetRow(txtTip, 3);
                    Grid.SetColumn(txtTip, 1);
                    GridCloseCheckTypeStrip.Children.Add(txtTip);

                    #endregion

                    #region Tax

                    TextBlock lblTax = new TextBlock();
                    lblTax.Text = "Tax";
                    lblTax.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                    lblTax.FontSize = 20;
                    lblTax.Margin = new Thickness(5, 4, 4, 0);
                    Grid.SetRow(lblTax, 4);
                    Grid.SetColumn(lblTax, 0);
                    GridCloseCheckTypeStrip.Children.Add(lblTax);

                    TextBlock txtTax = new TextBlock();
                    txtTax.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    txtTax.Width = 170;
                    decimal dTax = Math.Round((bTaxExempt) ? 0 : (iTotal * (decimal)(Globals.tax_rate)), 2);
                    txtTax.Text = dTax.ToString("N");
                    txtTax.FontSize = 20;
                    txtTax.Margin = new Thickness(16, 4, 0, 0);
                    Grid.SetRow(txtTax, 4);
                    Grid.SetColumn(txtTax, 1);
                    GridCloseCheckTypeStrip.Children.Add(txtTax);

                    #endregion

                    #region Total

                    TextBlock lblTotal = new TextBlock();
                    lblTotal.Text = "Total";
                    lblTotal.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                    lblTotal.FontSize = 20;
                    lblTotal.Margin = new Thickness(5, 4, 4, 0);
                    Grid.SetRow(lblTotal, 5);
                    Grid.SetColumn(lblTotal, 0);
                    GridCloseCheckTypeStrip.Children.Add(lblTotal);

                    TextBlock txtTotal = new TextBlock();
                    txtTotal.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    txtTotal.Width = 170;

                    decimal dTip, dTotal;
                    // Get the gratuity...
                    try
                    {
                        dTip = Convert.ToDecimal(txtTip.Text);
                    }
                    catch (FormatException)
                    {
                        dTip = 0;
                    }

                    // Determine the total, based on subtotal, tax, and tip
                    dTotal = iTotal + Convert.ToDecimal(txtTax.Text) + dTip;
                    txtTotal.Text = Convert.ToDecimal(dTotal).ToString("N");

                    txtTotal.FontSize = 20;
                    txtTotal.Margin = new Thickness(16, 4, 0, 0);
                    Grid.SetRow(txtTotal, 5);
                    Grid.SetColumn(txtTotal, 1);
                    GridCloseCheckTypeStrip.Children.Add(txtTotal);

                    #endregion

                    #region Payment


                    TextBlock lblPayment = new TextBlock();

                    lblPayment.Text = "Payment ";
                    lblPayment.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                    lblPayment.FontSize = 20;
                    lblPayment.Margin = new Thickness(5, 4, 5, 0);
                    Grid.SetRow(lblPayment, 6);
                    Grid.SetColumn(lblPayment, 0);
                    GridCloseCheckTypeStrip.Children.Add(lblPayment);

                    // Default to a numeric keyboard
                    InputScope paymentScope = new InputScope();
                    InputScopeName paymentScopeName = new InputScopeName();
                    paymentScopeName.NameValue = InputScopeNameValue.Number;
                    paymentScope.Names.Add(paymentScopeName);

                    TextBox txtPayment = new TextBox();
                    txtPayment.InputScope = paymentScope;
                    txtPayment.Name = "txtPayment" + tmpCount;
                    txtPayment.TextChanged += txtTip_TextChanged;
                    txtPayment.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    txtPayment.Width = 170;
                    txtPayment.Tag = Globals.OrderCheckRecords[tmpCount].col_ID;
                    txtPayment.Text = Globals.OrderCheckRecords[tmpCount].col_AmountTendered.ToString("N");
                    txtPayment.FontSize = 20;
                    txtPayment.Margin = new Thickness(5, -3, 0, 0);
                    txtPayment.MaxLength = 10;
                    txtPayment.SelectionHighlightColor = new SolidColorBrush(highlightColor);
                    Grid.SetRow(txtPayment, 6);
                    Grid.SetColumn(txtPayment, 1);
                    GridCloseCheckTypeStrip.Children.Add(txtPayment);

                    #endregion

                    #region Change

                    TextBlock lblChange = new TextBlock();
                    lblChange.Text = "Change ";
                    lblChange.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                    lblChange.FontSize = 20;
                    lblChange.Margin = new Thickness(5, 4, 5, 0);
                    Grid.SetRow(lblChange, 7);
                    Grid.SetColumn(lblChange, 0);
                    GridCloseCheckTypeStrip.Children.Add(lblChange);

                    TextBox txtChange = new TextBox();
                    txtChange.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    txtChange.Width = 170;
                    decimal change = (Convert.ToDecimal(Globals.OrderCheckRecords[tmpCount].col_AmountTendered) - dTotal);
                    change = (change < 0 ? 0 : change);
                    txtChange.Text = change.ToString("N");
                    txtChange.FontSize = 20;
                    txtChange.Margin = new Thickness(5, 0, 0, 0);
                    txtChange.IsEnabled = false;
                    Grid.SetRow(txtChange, 7);
                    Grid.SetColumn(txtChange, 1);
                    GridCloseCheckTypeStrip.Children.Add(txtChange);

                    #endregion

                    #region Auth code

                    TextBlock lblAuthCode = new TextBlock();
                    lblAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    lblAuthCode.Text = "Auth Code ";
                    lblAuthCode.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                    lblAuthCode.FontSize = 20;
                    lblAuthCode.Margin = new Thickness(5, 12, 5, 0);
                    Grid.SetRow(lblAuthCode, 8);
                    Grid.SetColumn(lblAuthCode, 0);
                    GridCloseCheckTypeStrip.Children.Add(lblAuthCode);

                    TextBox txtAuthCode = new TextBox();
                    txtAuthCode.Name = "txtAuthCode" + tmpCount;
                    txtAuthCode.TextChanged += txtAuthCode_TextChanged;
                    txtAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    txtAuthCode.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    txtAuthCode.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    txtAuthCode.Width = 170;
                    txtAuthCode.Height = 35;
                    txtAuthCode.Text = Globals.OrderCheckRecords[tmpCount].col_AuthCode == null ? "" : Globals.OrderCheckRecords[tmpCount].col_AuthCode;
                    txtAuthCode.FontSize = 20;
                    txtAuthCode.Margin = new Thickness(5, 12, 0, 0);
                    txtAuthCode.MaxLength = 50;
                    txtAuthCode.SelectionHighlightColor = new SolidColorBrush(highlightColor);
                    Grid.SetRow(txtAuthCode, 8);
                    Grid.SetColumn(txtAuthCode, 1);
                    GridCloseCheckTypeStrip.Children.Add(txtAuthCode);

                    #endregion


                    Grid.SetRow(GridCloseCheckTypeStrip, 4);
                    GridSplitCheck.Children.Add(GridCloseCheckTypeStrip);

                    #endregion


                    #region create footer for button

                    /*create footer for button*/
                    Grid GridSplitCheckFooterForbutton = new Grid();
                    GridSplitCheckFooterForbutton.Background = new SolidColorBrush(Colors.White);
                    gridCol1 = new ColumnDefinition();
                    gridCol2 = new ColumnDefinition();

                    GridSplitCheckFooterForbutton.ColumnDefinitions.Add(gridCol1);
                    GridSplitCheckFooterForbutton.ColumnDefinitions.Add(gridCol2);

                    // Set remove button 
                    Button btnCloseCheck = new Button() { Content = "Close", CommandParameter = tmpCount, FontSize = 20 };
                    btnCloseCheck.Tapped += btnCloseCheck_Tapped;

                    ToolTip toolTip = new ToolTip();
                    toolTip.Content = "Close check";
                    ToolTipService.SetToolTip(btnCloseCheck, toolTip);
                    btnCloseCheck.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    btnCloseCheck.Width = 120;
                    btnCloseCheck.Height = 60;
                    btnCloseCheck.Margin = new Thickness(5, 10, 0, 0);
                    Grid.SetColumn(btnCloseCheck, 0);
                    GridSplitCheckFooterForbutton.Children.Add(btnCloseCheck);


                    // Set remove button 
                    Button btnPrintCheck = new Button() { Content = "Print", CommandParameter = tmpCount, FontSize = 20 };
                    btnPrintCheck.Tapped += btnPrintCheck_Tapped;

                    toolTip = new ToolTip();
                    toolTip.Content = "Print check";
                    ToolTipService.SetToolTip(btnPrintCheck, toolTip);
                    btnPrintCheck.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    btnPrintCheck.Width = 120;
                    btnPrintCheck.Height = 60;
                    btnPrintCheck.HorizontalAlignment = HorizontalAlignment.Right;
                    btnPrintCheck.Margin = new Thickness(0, 10, 5, 0);
                    Grid.SetColumn(btnPrintCheck, 1);
                    GridSplitCheckFooterForbutton.Children.Add(btnPrintCheck);

                    Grid.SetRow(GridSplitCheckFooterForbutton, 5);
                    GridSplitCheck.Children.Add(GridSplitCheckFooterForbutton);

                    #endregion



                    tmpBorder.Child = GridSplitCheck;
                    tmpCanvas.Children.Add(tmpBorder);

                    if (tmpCount > 2) SplitChecksContainer.Width = SplitChecksContainer.Width + 300;

                    Thumb thumb = new Thumb();

                    tmpCanvas.Children.Add(thumb);

                    SplitChecksContainer.Children.Add(tmpCanvas);
                    // set payment mode radio button click based on saved option

                    if (rdbHeaderGridCloseCheckType1.IsChecked == true)
                    {
                        rdbHeaderGridCloseCheckType1_Checked(rdbHeaderGridCloseCheckType1, null);
                    }
                    else if (rdbHeaderGridCloseCheckType2.IsChecked == true)
                    {
                        rdbHeaderGridCloseCheckType1_Checked(rdbHeaderGridCloseCheckType2, null);
                    }
                    else
                    {
                        rdbHeaderGridCloseCheckType1_Checked(rdbHeaderGridCloseCheckType3, null);
                    }

                    if (Globals.OrderCheckRecords[tmpCount].col_Paid) EnableDisable_SplitCheckControls(tmpCount);
                    else
                    {
                        btnCloseCheck.IsEnabled = true; //change > 0;
                        btnPrintCheck.IsEnabled = true;
                    }
                    SplitChecksContainer.UpdateLayout();
                }
                catch (Exception ex)
                {
                    iSplitCount = SplitChecksContainer.Children.Count;
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
                tmpCount++;
            }
        }

        async void txtAuthCode_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender == null) return;

            string name = ((Windows.UI.Xaml.FrameworkElement)(sender)).Name;
            if (string.IsNullOrWhiteSpace(name)) return;

            string checkNo = name.Remove(0, 11); // check this is from tip or payment textbox 

            if (string.IsNullOrWhiteSpace(checkNo)) return;

            Grid childGrid = GetPaymentGridFromCheckNo(checkNo);
            await calculatePayment(childGrid, -1, true);
        }

        void btnCloseCheck_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button btnCross = sender as Button;
            if (btnCross != null) CloseCheck(btnCross.CommandParameter);
        }

        void btnPrintCheck_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button btnCross = sender as Button;
            if (btnCross != null) PrintCheck(btnCross.CommandParameter);
        }


        public async void ClosePartialCheck(object checkNo)
        {
            // Display the wait page...
            WaitPage waitPage = new WaitPage();
            waitPage.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            waitPage.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
            Popup dialogPopup = new Popup();
            dialogPopup.Child = waitPage;

            if (checkNo == null)
                return;

            try
            {
                dialogPopup.IsOpen = true;
                string checkNumber = Convert.ToString(checkNo);

                Grid childGrid = GetPaymentGridFromCheckNo(checkNumber);
                if (childGrid == null) return;

                await calculatePayment(childGrid, Convert.ToInt32(checkNumber));

                //Disable  buttons 
                FooterButtonsEnableDisable(Convert.ToInt32(checkNumber), false);

                bool bAllPaid = true;
                foreach (ServiceReferenceOpenRPOS.OrderCheck oc in Globals.OrderCheckRecords)
                {
                    if (oc.col_Paid) EnableDisable_SplitCheckControls(oc.col_SeatNumber);
                    bAllPaid &= oc.col_Paid;
                }

                // Close the entire order if all checks have been paid...
                // Send close request    
                if (this.CloseRequested != null && bAllPaid)
                {
                    this.CloseRequested(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                dialogPopup.IsOpen = false;
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            finally
            {
                dialogPopup.IsOpen = false;
            }
        }


        private async void CloseCheck(object checkNo)
        {
            // Display the wait page...
            WaitPage waitPage = new WaitPage();
            waitPage.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            waitPage.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
            Popup dialogPopup = new Popup();
            dialogPopup.Child = waitPage;

            if (checkNo == null)
                return;

            try
            {

                dialogPopup.IsOpen = true;
                string checkNumber = Convert.ToString(checkNo);
                iCheckNo = Convert.ToInt32(checkNo);
                Grid childGrid = GetPaymentGridFromCheckNo(checkNumber);
                if (childGrid == null) return;

                // Determine whether or not this should be processed as credit
                Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
                if (childPaymentGrid != null)
                {
                    RadioButton rdCreditDebit = ((RadioButton)childPaymentGrid.Children[2]) as RadioButton;
                    RadioButton rdOther = ((RadioButton)childPaymentGrid.Children[3]) as RadioButton;
                    ComboBox cbPaymentType = ((ComboBox)childPaymentGrid.Children[4]) as ComboBox;
                    TextBlock txtTax = ((TextBlock)childPaymentGrid.Children[8]) as TextBlock;
                    TextBlock txtTotal = ((TextBlock)childPaymentGrid.Children[10]) as TextBlock;
                    TextBox txtPayment = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                    TextBox txtGrat = ((TextBox)childPaymentGrid.Children[6]) as TextBox;
                    if (rdCreditDebit != null)
                    {
                        if (rdCreditDebit.IsChecked == true)
                        {
                            TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[16]) as TextBox;
                            txtAuthCode.IsEnabled = false;
                            if (Globals.processMercury)
                            {
                                // Handle the mercury transaction - Determine if a pre-auth has been performed...
                                ServiceReferenceOpenRPOS.Mercury mercuryRec;
                                Globals.MercuryRecords = await Globals.client.GetMercuryObjectsAsync(Globals.token, "OrderCheckID=" + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID.ToString());
                                if (Globals.MercuryRecords.Count() > 0)
                                    mercuryRec = Globals.MercuryRecords[0];
                                else
                                    mercuryRec = new ServiceReferenceOpenRPOS.Mercury();
                                if (!mercuryRec.col_Authorized)
                                {
                                    // Show the mercury dialog...
                                    MercuryDialog md = new MercuryDialog();
                                    md.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
                                    md.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
                                    md.CloseRequested += MercuryDialog_CloseRequested;
                                    md.mercuryRec = mercuryRec;
                                    decimal purch = Convert.ToDecimal(txtTotal.Text);
                                    decimal grat = Convert.ToDecimal(txtGrat.Text);
                                    decimal tax = Convert.ToDecimal(txtTax.Text);
                                    // If the check # is 0, create a new check record
                                    if (Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID==0)
                                    {
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSubtotal = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal = purch-tax;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterTax = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax = tax;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterGratuity = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Gratuity = grat;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSeatNumber = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_SeatNumber = Convert.ToByte(checkNo);
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterPaymentType = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_PaymentType = 1;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID = await Globals.client.AddOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)]);
                                    }

                                    md.init(purch, grat, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_OrderSummaryID);
                                    subDialogPopup = new Popup();
                                    subDialogPopup.Child = md;
                                    subDialogPopup.IsOpen = true;
                                    return;
                                }
                                else // Finalize transaction
                                {
                                    Grid childPaymentGrid2 = ((Grid)(((Panel)(childGrid)).Children[4]));
                                    TextBox txtTip = ((TextBox)childPaymentGrid.Children[6]) as TextBox;
                                    decimal dTip = 0;
                                    if (txtTip != null)
                                    {
                                        // Get the gratuity...
                                        try
                                        {
                                            dTip = Convert.ToDecimal(txtTip.Text);
                                        }
                                        catch (FormatException)
                                        {
                                            dTip = 0;
                                        }
                                    }

                                    ServiceReferenceMercury.PaymentRequest request = new ServiceReferenceMercury.PaymentRequest();
                                    request.AcqRefData = mercuryRec.col_AcqRefData;
                                    request.AuthCode = mercuryRec.col_AuthCode;
                                    request.InvoiceNo = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID;
                                    request.Memo = Globals.k_str_memo;
                                    request.OperatorID = Globals.currentLogin.col_UserName;
                                    request.LaneID = 0;
                                    request.RecordNo = mercuryRec.col_RecordNumber;
                                    request.RefNo = request.InvoiceNo.ToString();
                                    //request.Authorize = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax;
                                    request.Purchase = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax;
                                    request.Authorize = request.Purchase + dTip;
                                    request.Gratuity = dTip;
                                    ServiceReferenceMercury.PaymentResponse response = await Globals.mercuryClient.ProcessPostAuthAsync(request);
                                    System.Diagnostics.Debug.WriteLine(response.CmdStatus);
                                    // Update the mercury record...
                                    mercuryRec.bFilterPosted = true;
                                    mercuryRec.col_Posted = true;

                                    await Globals.client.UpdateMercuryObjectAsync(Globals.token, mercuryRec);
                                }
                            }
                            else if (Globals.processUSAePay)
                            {
                                // Handle USA ePay transaction - Determine if a pre-auth has been performed...
                                ServiceReferenceOpenRPOS.USAePay usaepayRec;
                                Globals.USAePayRecords = await Globals.client.GetUSAePayObjectsAsync(Globals.token, "OrderCheckID=" + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID.ToString());
                                if (Globals.USAePayRecords.Count() > 0)
                                    usaepayRec = Globals.USAePayRecords[0];
                                else
                                    usaepayRec = new ServiceReferenceOpenRPOS.USAePay();
                                if (!usaepayRec.col_Authorized)
                                {
                                    USAePayDialog ud = new USAePayDialog();
                                    ud.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
                                    ud.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
                                    ud.CloseRequested += USAePayDialog_CloseRequested;
                                    subDialogPopup = new Popup();
                                    subDialogPopup.Child = ud;
                                    subDialogPopup.IsOpen = true;
                                    /*
                                    decimal purch = Convert.ToDecimal(txtTotal.Text);
                                    decimal grat = Convert.ToDecimal(txtGrat.Text);
                                    decimal tax = Convert.ToDecimal(txtTax.Text);
                                     */
                                    decimal purch=0, grat=0, tax=0, tot=0;
                                    try{purch = Convert.ToDecimal(txtTotal.Text);} catch(Exception){purch=0;}
                                    try{grat = Convert.ToDecimal(txtGrat.Text);} catch(Exception){grat=0;}
                                    try{tax = Convert.ToDecimal(txtTax.Text);} catch(Exception){tax=0;}
                                    tot=purch+grat+tax;
                                    // If the check # is 0, create a new check record
                                    if (Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID == 0)
                                    {
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSubtotal = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal = purch - tax;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterTax = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax = tax;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterGratuity = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Gratuity = grat;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSeatNumber = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_SeatNumber = Convert.ToByte(checkNo);
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterPaymentType = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_PaymentType = 1;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID = await Globals.client.AddOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)]);
                                    }
                                    // Pass amount to process...
                                    ud.amount = tot;
                                    ud.invoiceNo = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID;
                                    ud.ordernumber = iOrderNO;
                                    ud.focusCapture();
                                    return;
                                }
                                else // Finalize transaction
                                {
                                    Grid childPaymentGrid2 = ((Grid)(((Panel)(childGrid)).Children[4]));
                                    TextBox txtTip = ((TextBox)childPaymentGrid.Children[6]) as TextBox;
                                    decimal dTip = 0;
                                    if (txtTip != null)
                                    {
                                        // Get the gratuity...
                                        try
                                        {
                                            dTip = Convert.ToDecimal(txtTip.Text);
                                        }
                                        catch (FormatException)
                                        {
                                            dTip = 0;
                                        }
                                    }
                                    ServiceReferenceUSAePay.PaymentRequest request = new ServiceReferenceUSAePay.PaymentRequest();
                                    request.InvoiceNo = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID;
                                    request.Amount = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax + dTip;
                                    request.SourceKey = Globals.strUSAePaySourceKey;
                                    request.Pin = Globals.strUSAePayPin;
                                    request.RefNum = usaepayRec.col_RefNum;
                                    ServiceReferenceUSAePay.PaymentResponse response = await Globals.usaepayClient.ProcessPostAuthAsync(request);
                                    System.Diagnostics.Debug.WriteLine(response.Result);
                                    // Update the USA ePay record...
                                    usaepayRec.bFilterPosted = true;
                                    usaepayRec.col_Posted = true;
                                    await Globals.client.UpdateUSAePayObjectAsync(Globals.token, usaepayRec);
                                }
                            }
                            else if (Globals.processBlackline)
                            {
                                // Handle the mercury transaction - Determine if a pre-auth has been performed...
                                ServiceReferenceOpenRPOS.Blackline blacklineRec;
                                Globals.BlacklineRecords = await Globals.client.GetBlacklineObjectsAsync(Globals.token, "OrderCheckID=" + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID.ToString());
                                if (Globals.BlacklineRecords.Count() > 0)
                                    blacklineRec = Globals.BlacklineRecords[0];
                                else
                                    blacklineRec = new ServiceReferenceOpenRPOS.Blackline();
                                if (blacklineRec.col_ResultCode != "Approved")
                                {
                                    decimal purch = Convert.ToDecimal(txtTotal.Text);
                                    decimal grat = Convert.ToDecimal(txtGrat.Text);
                                    decimal tax = Convert.ToDecimal(txtTax.Text);
                                    // If the check # is 0, create a new check record
                                    if (Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID == 0)
                                    {
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSubtotal = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal = purch - tax;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterTax = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax = tax;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterGratuity = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Gratuity = grat;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSeatNumber = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_SeatNumber = Convert.ToByte(checkNo);
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterPaymentType = true;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_PaymentType = 1;
                                        Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID = await Globals.client.AddOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)]);
                                    }

                                    // Show the blackline dialog...
                                    BlacklineDialog bd = new BlacklineDialog();
                                    bd.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
                                    bd.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
                                    bd.CloseRequested += BlacklineDialog_CloseRequested;
                                    subDialogPopup = new Popup();
                                    subDialogPopup.Child = bd;
                                    subDialogPopup.IsOpen = true;
                                    TextBox txtTip = ((TextBox)childPaymentGrid.Children[6]) as TextBox;
                                    decimal dTip = 0;
                                    if (txtTip != null)
                                    {
                                        // Get the gratuity...
                                        try
                                        {
                                            dTip = Convert.ToDecimal(txtTip.Text);
                                        }
                                        catch (FormatException)
                                        {
                                            dTip = 0;
                                        }
                                    }
                                    await bd.processSale(Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax + dTip, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID);
                                    return;
                                }
                                else // Finalize transaction
                                {
                                    Grid childPaymentGrid2 = ((Grid)(((Panel)(childGrid)).Children[4]));
                                    TextBox txtTip = ((TextBox)childPaymentGrid.Children[6]) as TextBox;
                                    decimal dTip = 0;
                                    if (txtTip != null)
                                    {
                                        // Get the gratuity...
                                        try
                                        {
                                            dTip = Convert.ToDecimal(txtTip.Text);
                                        }
                                        catch (FormatException)
                                        {
                                            dTip = 0;
                                        }
                                    }
                                    // Perform a tip adjustment...
                                    string exMessage = "";
                                    try
                                    {
                                        decimal in_amount = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal + Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax + dTip;
                                        int in_invoice = Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID;
                                        string requestUrl = Globals.strBlacklineUrl + "/runTransaction?command=tipadjust&key=" + Globals.strBlacklineKey + "&password=" + Globals.strBlacklinePassword + "&Amount=" + in_amount.ToString() + "&terminalID=" + Globals.strBlacklineTerminalID + "&refId=" + in_invoice.ToString();
                                        BlacklineJsonResponse jsonResponse;
                                        HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                                        HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
                                        System.Diagnostics.Debug.WriteLine(response.Headers.ToString());
                                        if (response.StatusCode != HttpStatusCode.OK)
                                            throw new Exception(String.Format(
                                            "Server error (HTTP {0}: {1}).",
                                            response.StatusCode,
                                            response.StatusDescription));
                                        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(BlacklineJsonResponse));
                                        object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                                        jsonResponse = objResponse as BlacklineJsonResponse;
                                        System.Diagnostics.Debug.WriteLine(jsonResponse.ResultCode);
                                        // If the adjustment is not approved, do not close the check...
                                        if (jsonResponse.ResultCode != "Approved")
                                        {
                                            // Display message for user...
                                            var messageDialog = new MessageDialog(jsonResponse.AuthCode + " " + jsonResponse.Message);
                                            await messageDialog.ShowAsync();
                                            
                                            System.Diagnostics.Debug.WriteLine(jsonResponse.AuthCode);
                                            // Don't close the check...
                                            return;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        exMessage = ex.Message;
                                    }
                                    if (exMessage != "")
                                    {
                                        // Display message for user...
                                        var messageDialog = new MessageDialog(exMessage);
                                        // Add command to close the dialog...
                                        messageDialog.Commands.Add(new UICommand("Close"));
                                        await messageDialog.ShowAsync();

                                        System.Diagnostics.Debug.WriteLine(exMessage);
                                        // Don't close the check...
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    if (rdOther != null)
                    {
                        if (rdOther.IsChecked == true)
                        {
                            if (cbPaymentType.SelectedItem.ToString() == "Partial Payment")
                            {
                                // Show the partial payment dialog...
                                decimal dPartial = 0;
                                decimal purch = Convert.ToDecimal(txtTotal.Text);
                                decimal grat = Convert.ToDecimal(txtGrat.Text);
                                decimal tax = Convert.ToDecimal(txtTax.Text);
                                // If the check # is 0, create a new check record
                                if (Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID == 0)
                                {
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSubtotal = true;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Subtotal = purch - tax;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterTax = true;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Tax = tax;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterGratuity = true;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_Gratuity = grat;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterSeatNumber = true;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_SeatNumber = Convert.ToByte(checkNo);
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].bFilterPaymentType = true;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_PaymentType = 1;
                                    Globals.OrderCheckRecords[Convert.ToInt32(checkNo)].col_ID = await Globals.client.AddOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[Convert.ToInt32(checkNo)]);
                                }

                                PartialPaymentDialog ppd = new PartialPaymentDialog();
                                ppd.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
                                ppd.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
                                ppd.CloseRequested += PartialPaymentDialog_CloseRequested;
                                ppd.checkNumber = checkNumber;
                                if (txtPayment != null && txtPayment.Text != "" && Convert.ToInt32(txtPayment.Tag) != 0)
                                {
                                    await GetPartialPaymentRecord(Convert.ToInt32(txtPayment.Tag));
                                    dPartial = Convert.ToDecimal(txtTotal.Text);
                                    ppd.Init(dPartial);
                                }
                                else
                                {
                                    dPartial = Convert.ToDecimal(txtTotal.Text);
                                    ppd.Init(dPartial);
                                }

                                subDialogPopup = new Popup();
                                subDialogPopup.Child = ppd;
                                subDialogPopup.IsOpen = true;
                                return;
                            }
                       }
                    }
                }

                await calculatePayment(childGrid, Convert.ToInt32(checkNumber));

                //Disable  buttons 
                FooterButtonsEnableDisable(Convert.ToInt32(checkNumber), false);

                bool bAllPaid = true;
                foreach (ServiceReferenceOpenRPOS.OrderCheck oc in Globals.OrderCheckRecords)
                {
                    if (oc.col_Paid) EnableDisable_SplitCheckControls(oc.col_SeatNumber);
                    bAllPaid &= oc.col_Paid;
                }

                // Close the entire order if all checks have been paid...
                // Send close request    
                if (this.CloseRequested != null && bAllPaid)
                {
                    this.CloseRequested(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                dialogPopup.IsOpen = false;
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            finally
            {
                dialogPopup.IsOpen = false;
            }
        }

        private void MercuryDialog_CloseRequested(object sender, EventArgs e)
        {
            MercuryDialog md = (MercuryDialog)sender;
            subDialogPopup.IsOpen = false;
        }

        private void MessageDialog_CloseRequested(object sender, EventArgs e)
        {
            subDialogPopup.IsOpen = false;
        }

        private void USAePayDialog_CloseRequested(object sender, EventArgs e)
        {
            USAePayDialog ud = (USAePayDialog)sender;
            subDialogPopup.IsOpen = false;
            // Update the auth code, if needed...
            if (ud.strAuthCode.Length > 0)
            {
                Globals.OrderCheckRecords[iCheckNo].bFilterAuthCode = true;
                Globals.OrderCheckRecords[iCheckNo].col_AuthCode = ud.strAuthCode;

                Grid childGrid = GetPaymentGridFromCheckNo(iCheckNo.ToString());
                if (childGrid == null) return;

                // Determine whether or not this should be processed as credit
                Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
                if (childPaymentGrid != null)
                {
                    TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[16]) as TextBox;
                    txtAuthCode.IsEnabled = false;
                }
            }
        }

        private void BlacklineDialog_CloseRequested(object sender, EventArgs e)
        {
            BlacklineDialog bd = (BlacklineDialog)sender;
            subDialogPopup.IsOpen = false;
            // Update the auth code, if needed...
            if (bd.strAuthCode.Length > 0)
            {
                Grid childGrid = GetPaymentGridFromCheckNo(iCheckNo.ToString());
                if (childGrid == null) return;
                Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
                if (childPaymentGrid != null)
                {
                    TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[16]) as TextBox;
                    txtAuthCode.Text = bd.strAuthCode;
                    txtAuthCode.IsEnabled = false;
                }
            }
        }
        private void PartialPaymentDialog_CloseRequested(object sender, EventArgs e)
        {
            PartialPaymentDialog ppd = (PartialPaymentDialog)sender;
            subDialogPopup.IsOpen = false;
            if (e != null)
            {
                ClosePartialCheck(partialCheckNo);
            }
        }

        void FooterButtonsEnableDisable(int checkNo, bool isEnable)
        {
            Grid childGrid = GetPaymentGridFromCheckNo(checkNo.ToString());
            if (childGrid == null) return;

            Grid childFooterButtonGrid = ((Grid)(((Panel)(childGrid)).Children[5]));
            if (childFooterButtonGrid != null)
            {
                Button btnClose = ((Button)childFooterButtonGrid.Children[0]) as Button;
                Button btnPrint = ((Button)childFooterButtonGrid.Children[1]) as Button;

                if (btnClose != null) btnClose.IsEnabled = isEnable;
                if (btnPrint != null) btnPrint.IsEnabled = isEnable;
            }

            EnabledisablePaidImage(isEnable, checkNo);
        }

        private async void PrintCheck(object checkNo)
        {

            // Display the wait page...
            WaitPage waitPage = new WaitPage();
            waitPage.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            waitPage.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
            Popup dialogPopup = new Popup();
            dialogPopup.Child = waitPage;

            try
            {
                if (checkNo == null)
                    return;

                dialogPopup.IsOpen = true;

                int checkNumber = Convert.ToInt32(checkNo);
                int tmpCount = 0;
                while (tmpCount < iSplitCount)
                {

                    Grid childGrid = GetPaymentGridFromCheckNo(tmpCount.ToString());
                    if (childGrid == null) continue;
                    if (!Globals.OrderCheckRecords[tmpCount].col_Paid)
                        await calculatePayment(childGrid, tmpCount, true, false);
                    tmpCount++;
                }
                //Disable  buttons 
                FooterButtonsEnableDisable(checkNumber, true);

                Globals.OrderCheckRecords = await Globals.client.GetOrderCheckObjectsAsync(Globals.token, "OrderSummaryID=" + iOrderNO + " ORDER BY SeatNumber");
                // Remove any excess records, if they exist
                if (Globals.OrderCheckRecords.Count() > iSplitCount)
                {
                    int cnt = Globals.OrderCheckRecords.Count();
                    for (int i = cnt; cnt > iSplitCount; cnt--)
                    {
                        await Globals.client.DeleteOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[cnt - 1]);
                        Globals.OrderCheckRecords.RemoveAt(cnt - 1);
                    }
                }

                // Update the print queue to print the order reciepts
                ServiceReferenceOpenRPOS.PrintQueue pq = new ServiceReferenceOpenRPOS.PrintQueue();
                pq.bFilterPrintOrder = true;
                pq.col_PrintOrder = false;
                pq.bFilterPrintReceipt = true;
                pq.col_PrintReceipt = true;
                pq.bFilterOrderCheckID = true;
                pq.col_OrderCheckID = Globals.OrderCheckRecords[checkNumber].col_ID;
                pq.bFilterOrderSummaryID = true;
                pq.col_OrderSummaryID = iOrderNO;
                pq.bFilterPrinted = true;
                pq.col_Printed = false;
                pq.bFilterPrintRoute = true;
                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                Object value = localSettings.Values[Globals.k_str_settings_receipt_print_route];
                try
                {
                    pq.col_PrintRoute = Convert.ToByte(value);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
                try
                {
                    await Globals.client.AddPrintQueueObjectAsync(Globals.token, pq);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
            catch (Exception ex)
            {
                dialogPopup.IsOpen = false;
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                dialogPopup.IsOpen = false;
            }
        }

        async void txtTip_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender == null) return;

            string name = ((Windows.UI.Xaml.FrameworkElement)(sender)).Name;
            if (string.IsNullOrWhiteSpace(name)) return;

            string checkNo = (name.Contains("txtTip") ? name.Remove(0, 6) : name.Remove(0, 10)); // check this is from tip or payment textbox 

            if (string.IsNullOrWhiteSpace(checkNo)) return;

            Grid childGrid = GetPaymentGridFromCheckNo(checkNo);
            await calculatePayment(childGrid, -1, true);
        }

        private async Task<bool> calculatePayment(Grid childGrid, int checkNo = -1, bool fromPaymentChange = false, bool bClosing = true)
        {
            bool bResult, isPartial = false;

            ServiceReferenceOpenRPOS.PartialPayment partialpayment;
            if (childGrid == null) return false;

            int OrderCheckId=0;
            decimal dTip = 0, dSubtotal = 0, dTax = 0, payment = 0;
            Grid childFooterGrid = ((Grid)(((Panel)(childGrid)).Children[3]));
            if (childFooterGrid != null)
            {
                // Get Sub Total 
                TextBlock lblTotal = ((TextBlock)childFooterGrid.Children[1]) as TextBlock;
                if (lblTotal != null)
                {
                    dSubtotal = Convert.ToDecimal(lblTotal.Text);
                }
            }

            Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
            if (childPaymentGrid != null)
            {

                RadioButton rdCash = ((RadioButton)childPaymentGrid.Children[1]) as RadioButton;
                RadioButton rdCreditDebit = ((RadioButton)childPaymentGrid.Children[2]) as RadioButton;
                RadioButton rdOther = ((RadioButton)childPaymentGrid.Children[3]) as RadioButton;

                TextBox txtTip = ((TextBox)childPaymentGrid.Children[6]) as TextBox;

                TextBlock txtTax = ((TextBlock)childPaymentGrid.Children[8]) as TextBlock;
                TextBlock txtTotal = ((TextBlock)childPaymentGrid.Children[10]) as TextBlock;
                TextBox txtPayment = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                TextBox txtChange = ((TextBox)childPaymentGrid.Children[14]) as TextBox;
                TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[16]) as TextBox;
                ComboBox cbPaymentType = ((ComboBox)childPaymentGrid.Children[4]) as ComboBox;

                if (txtTip != null)
                {
                    // Get the gratuity...
                    try
                    {
                        dTip = Convert.ToDecimal(txtTip.Text);
                    }
                    catch (FormatException)
                    {
                        dTip = 0;
                    }
                }

                if (txtTax != null)
                {
                    // Get the Tax...
                    try
                    {
                        dTax = Convert.ToDecimal(txtTax.Text);
                    }
                    catch (FormatException)
                    {
                        dTax = 0;
                    }
                }

                if (txtTotal != null) txtTotal.Text = (dSubtotal + dTax + dTip).ToString("N");

                if (txtPayment != null)
                {
                    // Get the Payment...
                    try
                    {
                        payment = Convert.ToDecimal(txtPayment.Text);
                    }
                    catch (FormatException)
                    {
                        payment = 0;
                    }
                }

                // If payment is 0, assume exact change...
                if (payment < (dSubtotal + dTax + dTip) && bClosing)
                    payment = (dSubtotal + dTax + dTip);

                // get Change 
                decimal dChange = payment - (dSubtotal + dTax + dTip);
                dChange = (dChange < 0) ? 0 : dChange;

                if (txtChange != null) txtChange.Text = (dChange).ToString("N");
                string Authcode = string.Empty;
                if (txtAuthCode != null) Authcode = txtAuthCode.Text; // Add Auth code 
                // Assume the check is paid if "Close" is hit
                bool ispaid = true;

                if (!bClosing)
                {
                    if (rdCreditDebit != null && rdCreditDebit.IsChecked == true)
                        ispaid = (string.IsNullOrWhiteSpace(Authcode) == false);
                    else if (rdCash != null && rdCash.IsChecked == true)
                        ispaid = (payment - (dSubtotal + dTax + dTip) >= 0);
                }

                // Save order details  if it is from ok button 
                if (checkNo > -1)
                {
                    Globals.OrderCheckRecords[checkNo].col_Gratuity = dTip; // Set Gratuity 
                    Globals.OrderCheckRecords[checkNo].bFilterGratuity = true;

                    Globals.OrderCheckRecords[checkNo].col_Tax = dTax;  // Set tax
                    Globals.OrderCheckRecords[checkNo].bFilterTax = true;
                    Globals.OrderCheckRecords[checkNo].col_Subtotal = dSubtotal;  // Set  Sub total 
                    Globals.OrderCheckRecords[checkNo].bFilterSubtotal = true;
                    Globals.OrderCheckRecords[checkNo].col_SeatNumber = Convert.ToByte(checkNo);
                    Globals.OrderCheckRecords[checkNo].bFilterSeatNumber = true;
                    Globals.OrderCheckRecords[checkNo].bFilterPaymentType = true;
                    Globals.OrderCheckRecords[checkNo].bFilterPaid = true;

                    if (rdCreditDebit != null && rdCreditDebit.IsChecked == true)
                    {
                        Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        Globals.OrderCheckRecords[checkNo].bFilterAuthCode = true;
                        if (txtAuthCode != null) Globals.OrderCheckRecords[checkNo].col_AuthCode = txtAuthCode.Text; // Add Auth code 
                        Globals.OrderCheckRecords[checkNo].col_PaymentType = 1;  // Set payment type 1 for Creditdebit
                    }
                    else if (rdCash != null && rdCash.IsChecked == true)
                    {
                        Globals.OrderCheckRecords[checkNo].col_PaymentType = 0;  // Set payment type 0 for Cash 
                        Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        Globals.OrderCheckRecords[checkNo].col_AmountTendered = payment; // Set AmountTendered
                        Globals.OrderCheckRecords[checkNo].bFilterAmountTendered = true;
                        // Kick the cash drawer, on close...
                        if (bClosing)
                            bResult = await Globals.OpenDrawer();
                    }
                    else if (rdOther != null && rdOther.IsChecked == true)
                    {
                        Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        Globals.OrderCheckRecords[checkNo].col_PaymentType = Globals.PaymentTypeRecords[cbPaymentType.SelectedIndex].col_ID; // Set payment type for Other
                        Globals.OrderCheckRecords[checkNo].bFilterPaymentType = true;

                        if (cbPaymentType.SelectedItem.ToString() == "Partial Payment")
                        {
                            isPartial = true;
                        }
                    }
                }

                // Save order details  if it is from ok button 
                if (checkNo > -1)
                {
                    if (!fromPaymentChange)
                    {
                        Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        if (Globals.OrderCheckRecords[checkNo].col_Paid) EnableDisable_SplitCheckControls(checkNo);
                    }
                    else if (txtPayment != null && txtAuthCode != null)
                    {
                        if ((txtPayment.IsEnabled == false || txtAuthCode.IsEnabled == false) && ispaid)
                        {
                            Globals.OrderCheckRecords[checkNo].bFilterPaid = ispaid;
                            Globals.OrderCheckRecords[checkNo].col_Paid = ispaid;
                        }
                    }

                    // Send the updated record...
                    if (checkNo == Globals.OrderCheckRecords[checkNo].col_SeatNumber)
                    {
                        if (Globals.OrderCheckRecords[checkNo].col_ID == 0)
                        {
                            // Need to add a new record
                            OrderCheckId = await Globals.client.AddOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[checkNo]);
                            if (isPartial == true)
                            {
                                partialpayment = new ServiceReferenceOpenRPOS.PartialPayment();
                                partialpayment.col_PaymentType = 0;
                                partialpayment.bFilterPaymentType = true;
                                partialpayment.col_Amount = partialCashAmount;
                                partialpayment.bFilterAmount = true;
                                partialpayment.col_OrderCheckID = OrderCheckId;
                                partialpayment.bFilterOrderCheckID = true;
                                await Globals.client.AddPartialPaymentObjectAsync(Globals.token, partialpayment);
                                partialpayment = new ServiceReferenceOpenRPOS.PartialPayment();
                                partialpayment.col_PaymentType = 1;
                                partialpayment.bFilterPaymentType = true;
                                partialpayment.col_Amount = partialCreditAmount;
                                partialpayment.bFilterAmount = true;
                                partialpayment.col_OrderCheckID = OrderCheckId;
                                partialpayment.bFilterOrderCheckID = true;
                                await Globals.client.AddPartialPaymentObjectAsync(Globals.token, partialpayment);
                            }
                        }
                        else
                        {
                            // Update this record
                            await Globals.client.UpdateOrderCheckObjectAsync(Globals.token, Globals.OrderCheckRecords[checkNo]);
                            Globals.PartialPaymentRecords = await Globals.client.GetPartialPaymentObjectsAsync(Globals.token, "OrderCheckID=" + Globals.OrderCheckRecords[checkNo].col_ID + " ORDER BY OrderCheckID");
                            if (Globals.PartialPaymentRecords.Count > 0)
                            {
                                Globals.PartialPaymentRecords[0].col_PaymentType = 0;
                                Globals.PartialPaymentRecords[0].bFilterPaymentType = true;
                                Globals.PartialPaymentRecords[0].col_Amount = partialCashAmount;
                                Globals.PartialPaymentRecords[0].bFilterAmount = true;
                                Globals.PartialPaymentRecords[0].col_OrderCheckID = Globals.OrderCheckRecords[checkNo].col_ID;
                                Globals.PartialPaymentRecords[0].bFilterOrderCheckID = true;
                                await Globals.client.UpdatePartialPaymentObjectAsync(Globals.token, Globals.PartialPaymentRecords[0]);
                                Globals.PartialPaymentRecords[1].col_PaymentType = 1;
                                Globals.PartialPaymentRecords[1].bFilterPaymentType = true;
                                Globals.PartialPaymentRecords[1].col_Amount = partialCreditAmount;
                                Globals.PartialPaymentRecords[1].bFilterAmount = true;
                                Globals.PartialPaymentRecords[1].col_OrderCheckID = Globals.OrderCheckRecords[checkNo].col_ID;
                                Globals.PartialPaymentRecords[1].bFilterOrderCheckID = true;
                                await Globals.client.UpdatePartialPaymentObjectAsync(Globals.token, Globals.PartialPaymentRecords[1]);
                            } 
                        }       
                    }
                }
            }
            return true;
        }

        private async Task GetPartialPaymentRecord(int Id)
        {
            // Get the order check records
            Globals.OrderPartialCheckRecords = await Globals.client.GetOrderCheckObjectsAsync(Globals.token, "ID=" + Id + "");
        }

        private Grid GetPaymentGridFromCheckNo(string checkNo)
        {
            Canvas selectedControl = SplitChecksContainer.Children[Convert.ToInt32(checkNo)] as Canvas;
            if (selectedControl != null)
            {
                Border childBorder = ((Border)(((Panel)(selectedControl)).Children[0]));
                if (childBorder == null) return null;

                if (childBorder.Child != null)
                {
                    return childBorder.Child as Grid;
                }
            }
            return null;
        }

        void rdbHeaderGridCloseCheckType1_Checked(object sender, RoutedEventArgs e)
        {
            string parameter = Convert.ToString(((Windows.UI.Xaml.Controls.Primitives.ButtonBase)(sender)).CommandParameter);
            string Checkno = Convert.ToString(((RadioButton)(sender)).GroupName);

            // check if check number and radio button  are  valid
            if (string.IsNullOrWhiteSpace(Checkno) || string.IsNullOrWhiteSpace(parameter))
            {
                return;
            }

            Grid childGrid = GetPaymentGridFromCheckNo(Checkno);
            if (childGrid != null)
            {
                Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
                if (childPaymentGrid != null)
                {
                    TextBlock lblPayment = ((TextBlock)childPaymentGrid.Children[11]) as TextBlock;
                    TextBox txtPayment = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                    TextBlock lblChange = ((TextBlock)childPaymentGrid.Children[13]) as TextBlock;
                    TextBox txtChange = ((TextBox)childPaymentGrid.Children[14]) as TextBox;
                    TextBlock lblAuthCode = ((TextBlock)childPaymentGrid.Children[15]) as TextBlock;
                    TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[16]) as TextBox;
                    ComboBox cbPaymentType = ((ComboBox)childPaymentGrid.Children[4]) as ComboBox;

                    childPaymentGrid.RowDefinitions[8].Height = new GridLength(0);
                    childPaymentGrid.RowDefinitions[7].Height = new GridLength(0);
                    childPaymentGrid.RowDefinitions[6].Height = new GridLength(0);


                    if (lblPayment != null) lblPayment.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (txtPayment != null) txtPayment.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (lblChange != null) lblChange.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (txtChange != null) txtChange.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (lblAuthCode != null) lblAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (txtAuthCode != null) txtAuthCode.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (cbPaymentType != null) cbPaymentType.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                    switch (parameter)
                    {
                        case "Cash":
                            if (lblPayment != null) lblPayment.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (txtPayment != null) txtPayment.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (lblChange != null) lblChange.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            if (txtChange != null) txtChange.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            txtPayment.IsEnabled = true;
                            childPaymentGrid.RowDefinitions[6].Height = new GridLength(35);
                            childPaymentGrid.RowDefinitions[7].Height = new GridLength(35);
                            childPaymentGrid.Height = 290;
                            break;
                        case "CreditDebit":
                            // Don't display "Auth Code" label when using integrated credit processing...
                            if (!(Globals.processMercury||Globals.processUSAePay))
                            {
                                if (lblAuthCode != null) lblAuthCode.Visibility = Windows.UI.Xaml.Visibility.Visible;
                                if (txtAuthCode != null) txtAuthCode.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            }
                            childPaymentGrid.RowDefinitions[8].Height = new GridLength(70);
                            childPaymentGrid.Height = 290;
                            break;
                        case "Other":
                             if (cbPaymentType != null) cbPaymentType.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            childPaymentGrid.Height = 290;
                            childPaymentGrid.RowDefinitions[3].Height = new GridLength(35);
                            childPaymentGrid.RowDefinitions[6].Height = new GridLength(35);
                            childPaymentGrid.RowDefinitions[7].Height = new GridLength(35);
                            break;
                    }
                }
            }
        }

        private void MoveItemsInChecks(ListView SenderListview, ListView ReceiverListview)
        {
            if (ReceiverListview == null || SenderListview == null) return; //return and do nothing, if source or destination list object is null or not create 
            int checkNo = Convert.ToInt32(ReceiverListview.Tag);
            List<object> selectedItems = new List<object>();
            foreach (OrderData od in SenderListview.Items)
            {
                if (od.Parent != null) continue;

                if (od.SeatNumber == checkNo)
                {
                    od.SeatNumber = checkNo;
                    ReceiverListview.Items.Add(od);
                    selectedItems.Add(od);
                    if (od.Options != null)
                    {
                        foreach (OrderData odt in od.Options)
                        {
                            ReceiverListview.Items.Add(odt);
                            od.SeatNumber = checkNo;
                            selectedItems.Add(od);
                        }
                    }
                }
            }

            foreach (OrderData od in selectedItems)
            {
                if (od.Options != null)
                {
                    foreach (OrderData odt in od.Options)
                    {
                        SenderListview.Items.Remove(odt);
                    }
                }

                SenderListview.Items.Remove(od);
            }
        }


        public void setHeaderText(string strHeaderText)
        {
            lblOrderNo.Text = Convert.ToString(iOrderNO);
            lblTableNo.Text = Convert.ToString(iTableNO);
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.CloseRequested(this, null);
        }

        void EnabledisablePaidImage(bool isEnable, int checkNo)
        {
            Canvas selectedControl = SplitChecksContainer.Children[Convert.ToInt32(checkNo)] as Canvas;
            if (selectedControl != null)
            {

                Thumb cThumb = selectedControl.Children[1] as Thumb;
                if (cThumb != null)
                {
                    if (isEnable == false)
                    {
                        cThumb.Style = this.Resources["MyThumbStyle"] as Style;
                        cThumb.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.Height = 800;
                        cThumb.Width = 300;
                    }
                    else
                    {
                        cThumb.Style = null;
                        cThumb.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch;
                        cThumb.Height = 0;
                        cThumb.Width = 0;
                    }
                }
            }
        }

        private void EnableDisable_SplitCheckControls(int checkNo)
        {
            bool isEnable = !Globals.OrderCheckRecords[checkNo].col_Paid;

            EnabledisablePaidImage(isEnable, checkNo);  // Set paid image 

            Grid childGrid = GetPaymentGridFromCheckNo(Convert.ToString(checkNo));
            if (childGrid == null) return;

            Grid childPaymentGrid = ((Grid)(((Panel)(childGrid)).Children[4]));
            if (childPaymentGrid != null)
            {
                RadioButton rdCash = ((RadioButton)childPaymentGrid.Children[1]) as RadioButton;
                RadioButton rdCreditDebit = ((RadioButton)childPaymentGrid.Children[2]) as RadioButton;
                RadioButton rdOther = ((RadioButton)childPaymentGrid.Children[3]) as RadioButton;

                TextBox txtTip = ((TextBox)childPaymentGrid.Children[6]) as TextBox;
                TextBox txtPayment = ((TextBox)childPaymentGrid.Children[12]) as TextBox;
                TextBox txtChange = ((TextBox)childPaymentGrid.Children[14]) as TextBox;
                TextBox txtAuthCode = ((TextBox)childPaymentGrid.Children[16]) as TextBox;
                ComboBox cbPaymentType = ((ComboBox)childPaymentGrid.Children[4]) as ComboBox;

                if (rdCash != null) rdCash.IsEnabled = isEnable;
                if (rdCreditDebit != null) rdCreditDebit.IsEnabled = isEnable;
                if (rdOther != null) rdOther.IsEnabled = isEnable;
                if (txtTip != null) txtTip.IsEnabled = isEnable;
                if (txtPayment != null) txtPayment.IsEnabled = isEnable;
                if (txtAuthCode != null) txtAuthCode.IsEnabled = isEnable;
                if (cbPaymentType != null) cbPaymentType.IsEnabled = isEnable;
            }

            Grid childFooterButtonGrid = ((Grid)(((Panel)(childGrid)).Children[5]));
            if (childFooterButtonGrid != null)
            {
                Button btnClose = ((Button)childFooterButtonGrid.Children[0]) as Button;
                Button btnPrint = ((Button)childFooterButtonGrid.Children[1]) as Button;

                if (btnClose != null) btnClose.IsEnabled = isEnable;
                if (btnPrint != null) btnPrint.IsEnabled = isEnable;
            }
        }
    }
}
